package com.cyx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

//AOP 拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
//    private DataSource dataSource;

    //http层面 安全
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //校验授权
        http.authorizeRequests()
                //首页可以任意访问
                .antMatchers("/").permitAll()
                .antMatchers("/vip1/**").hasRole("vip1")
                .antMatchers("/vip2/**").hasRole("vip2")
                .antMatchers("/vip3/**").hasRole("vip3");

        //没有权限默认跳转至登录页面
        http.formLogin();
        //开启注销功能
        http.logout();

    }

    /**
     * 校验
     * - 注意密码需要编码
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //通过内存校验,正常业务应该通过数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("caoyx")
                .password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip1","vip2","vip3")
                .and()
                .withUser("jack")
                .password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip1");

//        auth.jdbcAuthentication().dataSource()
    }


}
